<?php
class process_provincias extends Controller {
	public function __construct() {
		parent::Controller();
		$this->load->model(array('provincias','paises','mcompania'));
		$this->load->helper(array('form','url'));
		$this->load->library(array('upload','form_validation'));
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
	}

	function index()
	{
		$this->load->view('main', array('content_page' => 'provincias_list','menutop' => 0, 'paises' => $this->__loadPaises(true)));
	}

	function add() {
		$this->load->view('main', array('content_page' => 'provincia_add','menutop' => 0, 'paises' => $this->__loadPaises(true)));
	}

	function edit($id_provincia) {
		$provincia = $this->provincias->LoadProvinciaById($id_provincia);
		$this->load->view('main', array('content_page' => 'provincia_edit','menutop' => 0, 'provincia' => $provincia, 'paises' => $this->__loadPaises()));
	}
	
	 function delete() 
	    {
			$ids = $this->input->post('delete_rows');
			if(strpos($ids,"|") === false) 
			{ 
				
				$num2 = $this->mcompania->LoadCompanyCantidad('IdProvincia',$ids);
				if ($num2 == 0) {	
			            if($this->provincias->Delete($ids) !== false)
			            {
				         echo 'El Registro fue eliminado satisfactoriamente';
			            }
			            else
			            {
				         echo 'Hubo un error eliminando el Registro.  Intentelo nuevamente mas tarde 						o comuniquese con el administrador';
			            }				
				}
				else 
				{
					echo 'Existe registro con este servicio';
				}
			
				
			} 
		
	    }



	function status()
	{
		$this->load->view('main', array('content_page' => 'status','menutop' => 0));
	}

	function save() {
		$this->form_validation->set_rules('name', '"Nombre"', 'trim|required');
		$this->form_validation->set_rules('country', '"Pais"', 'trim|required');

		if ($this->form_validation->run()) {
			$this->session->set_flashdata('status_title', 'Mantenimiento de Provincias');
			$this->session->set_flashdata('status_url', 'process_provincias');
			if($this->input->post('id_provincia') === false) {
				if($this->provincias->CreateProvincia($this->input->post('name'), $this->input->post('country')) != false)
				$this->session->set_flashdata('status_message', 'La provincia ha sido agregada satisfactoriamente');
				else
				$this->session->set_flashdata('status_message', 'Ha ocurrido un error agregando la provincia. Intentelo nuevamente mas tarde o comuniquese con el administrador');
			} else {
				$provincia = $this->provincias->LoadProvinciaById($this->input->post('id_provincia'));
				if($provincia != false) {
					$provincia->SetNombre($this->input->post('name'));
					$provincia->SetIdPais($this->input->post('country'));

					if($this->provincias->UpdateProvincia($provincia) != false)
					$this->session->set_flashdata('status_message', 'La provincia ha sido actualizada satisfactoriamente');
					else
					$this->session->set_flashdata('status_message', 'Ha ocurrido un error actualizando la provincia. Intentelo nuevamente mas tarde o comuniquese con el administrador');
				} else
				$this->session->set_flashdata('status_message', 'Ha ocurrido un error actualizando la provincia. Intentelo nuevamente mas tarde o comuniquese con el administrador');
			}
			redirect('process_provincias/status');
		}

		$view = 'provincia_add';
		$provincia = false;
		$selOpt = true;
		if($this->input->post('id_provincia') !== false) {
			$view = 'provincia_edit';
			$provincia = $this->provincias->LoadProvinciaById($this->input->post('id_provincia'));
			$selOpt = false;
		}

		$this->load->view('main', array('content_page' => $view, 'provincia' => $provincia, 'paises' => $this->__loadPaises($selOpt)));
	}

	function process_status() {
		$this->load->view('main', array('content_page' => 'status'));
	}

	function data() {
		$page = $this->input->post('page') ? $this->input->post('page') : 1; // Pagina Actual o 1 por default
		$sortname = $this->input->post('sidx') ? $this->input->post('sidx') : 'ID_airport'; // Columna para el order by
		$sortorder = $this->input->post('sord') ? $this->input->post('sord') : 'asc'; // Orden (asc|desc)
		$limit = $this->input->post('rows') ? $this->input->post('rows') : 10;
		$start = $limit * $page - $limit;
		if($start < 0) $start = 0;

		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
		header("Cache-Control: no-cache, must-revalidate" );
		header("Pragma: no-cache" );

		$records = $this->provincias->LoadProvincias($this->input->post('name'), $this->input->post('country'), $start, $limit, $sortname, $sortorder);

		$totalRecords = $this->provincias->GetCount($this->input->post('name'), $this->input->post('country'));

		$totalPages = ceil($totalRecords/$limit);
		if ($page > $totalPages) $page = $totalPages;

		$json_output = array(
		'page'		=> $page,
		'total'		=> $totalPages,
		'records'	=> $totalRecords,
		'rows'		=> array()
		);

		if($records != false) {
			foreach($records as $provincia) {
				$pais = $this->paises->LoadPaisById($provincia->GetIdPais());

				$arr = $json_output['rows'][] = array('id_provincia' => $provincia->GetIdProvincia(), 'nombre' => $provincia->GetNombre(), 'country' => $pais->GetNombre());
			}
		}

		echo json_encode($json_output);
	}

	function __loadPaises($selectOpt = false) {
		$paises = $this->paises->LoadPaises();

		$array_keys = array();
		$array_vals = array();

		if($selectOpt != false) {
			$array_keys[] = "";
			$array_vals[] = 'Seleccione un Pais';
		}

		$paises_arr = array();
		if ($paises != false) {
			foreach ($paises as $pais) {
				array_push($array_keys, $pais->GetIdPais());
				array_push($array_vals, $pais->GetNombre());
			}
		}
		if(count($array_keys) > 0)
		$paises_arr = array_combine($array_keys,$array_vals);

		return $paises_arr;
	}
}
?>